const pool = require("./db.js");

class UserDao {
    async registerUser(name, pwd) {
        try {
            const [rows, fields] = await pool.execute("INSERT INTO users(user_name, user_pwd) VALUES (?, ?)", [name, pwd]);
            return rows;
        } catch (err) {
            console.error("Error registering user:", err);
            throw err;
        }
    }

    async loginUser(name, pwd) {
        try {
            const [rows, fields] = await pool.execute("SELECT * FROM users WHERE user_name = ? AND user_pwd = ?", [name, pwd]);
            return rows[0];
        } catch (err) {
            console.error("Error logging in user:", err);
            throw err;
        }
    }

    async selectByName(name) {
        try {
            const [rows, fields] = await pool.execute("SELECT DISTINCT user_name FROM users WHERE user_name = ?", [name]);
            return rows.length > 0 ? rows[0] : null;
        } catch (err) {
            console.error("Error selecting user by name:", err);
            throw err;
        }
    }

    async selectById(id) {
        try {
            const [rows, fields] = await pool.execute("SELECT DISTINCT * FROM users WHERE user_id = ?", [id]);
            return rows.length > 0 ? rows[0] : null;
        } catch (err) {
            console.error("Error selecting user by ID:", err);
            throw err;
        }
    }

    async updataUserSelectedGroupID(userId, groupId){
        try {
            const [rows, fields] = await pool.execute(
                "UPDATE users SET group_id = ? WHERE user_id = ?",
                [groupId, userId]
            );
            return rows;
        } catch (err) {
            console.error("Error updating user selected group ID:", err);
            throw err;
        }
    }
}

module.exports = new UserDao();